package initization

import (
	"encoding/json"
	"fmt"
	"github.com/go-redis/redis"
	"github.com/nacos-group/nacos-sdk-go/v2/clients"
	"github.com/nacos-group/nacos-sdk-go/v2/common/constant"
	"github.com/nacos-group/nacos-sdk-go/v2/vo"
	"github.com/spf13/viper"
	"go.uber.org/zap"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"os"
	"srv/config"
	"srv/internal/model/dao"
)

var err error

func init() {
	ZapInit()
	ViperInit()
	NaCosInit()
	MysqlInit()
	RedisInit()
}
func ZapInit() {
	con := zap.NewDevelopmentConfig()
	con.OutputPaths = []string{
		"./srv.log",
		"stdout",
	}
	build, _ := con.Build()
	zap.ReplaceGlobals(build)
}
func ViperInit() {
	viper.SetConfigFile("./dev.yaml")
	err = viper.ReadInConfig()
	if err != nil {
		zap.S().Error("配置文件读取失败")
		return
	}
	err = viper.Unmarshal(&config.NaCosI)
	if err != nil {
		zap.S().Error("解析失败")
		return
	}
}
func NaCosInit() {
	err = os.MkdirAll("./tmp/nacos/log", 0777)
	if err != nil {
		zap.S().Error("文件创建失败")
		return
	}
	err = os.MkdirAll("./tmp/nacos/cache", 0777)
	if err != nil {
		zap.S().Error("文件创建失败")
		return
	}
	// 创建clientConfig
	clientConfig := constant.ClientConfig{
		NamespaceId:         config.NaCosI.NaCos.SpaceName, // 如果需要支持多namespace，我们可以创建多个client,它们有不同的NamespaceId。当namespace是public时，此处填空字符串。
		TimeoutMs:           5000,
		NotLoadCacheAtStart: true,
		LogDir:              "./tmp/nacos/log",
		CacheDir:            "./tmp/nacos/cache",
		LogLevel:            "debug",
	}
	// 至少一个ServerConfig
	serverConfigs := []constant.ServerConfig{
		{
			IpAddr:      config.NaCosI.NaCos.Host,
			ContextPath: "/nacos",
			Port:        config.NaCosI.NaCos.Port,
			Scheme:      "http",
		},
	}
	// 创建动态配置客户端的另一种方式 (推荐)
	configClient, _ := clients.NewConfigClient(
		vo.NacosClientParam{
			ClientConfig:  &clientConfig,
			ServerConfigs: serverConfigs,
		},
	)
	content, _ := configClient.GetConfig(vo.ConfigParam{
		DataId: config.NaCosI.NaCos.DataId,
		Group:  config.NaCosI.NaCos.Group})
	json.Unmarshal([]byte(content), &config.AppConfig)
}
func MysqlInit() {
	app := config.AppConfig.Mysql
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local", app.User, app.Password, app.Host, app.Port, app.Database)
	config.DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		zap.S().Error("数据库连接失败")
		return
	}
	err = config.DB.AutoMigrate(&dao.User{}, &dao.SaleInfo{})
	if err != nil {
		zap.S().Error("迁移失败")
		return
	}
}
func RedisInit() {
	config.Rdb = redis.NewClient(&redis.Options{
		Addr:     config.AppConfig.Redis.Host,
		Password: config.AppConfig.Redis.Password,
	})
	err = config.Rdb.Ping().Err()
	if err != nil {
		zap.S().Error("redis链接失败")
		return
	}
}
